<template>
  <el-switch
    v-model="themeConfig.isDark"
    inline-prompt
    :active-icon="Moon"
    :inactive-icon="Sunny"
    @change="switchDark"
  />
</template>

<script setup lang="ts" name="switchDark">
import { Sunny, Moon } from '@element-plus/icons-vue';
import { computed, onMounted } from 'vue';
import { useSettingStore } from '@/store/modules/setting';

const SettingStore = useSettingStore();
// 设置信息
const themeConfig = computed(() => SettingStore.themeConfig);

// 切换暗黑模式
const switchDark = () => {
  const html = document.documentElement;
  if (themeConfig.value.isDark) {
    html.classList.add('dark');
    // 添加 Element Plus 暗黑模式类
    document.body.setAttribute('class', 'el-dark');
  } else {
    html.classList.remove('dark');
    // 移除 Element Plus 暗黑模式类
    document.body.removeAttribute('class');
  }
};

// 初始化主题
onMounted(() => {
  // 从 localStorage 恢复主题设置
  const isDark = localStorage.getItem('settingState')
    ? JSON.parse(localStorage.getItem('settingState') || '{}').themeConfig?.isDark
    : false;

  if (isDark) {
    themeConfig.value.isDark = true;
    switchDark();
  }
});
</script>

<style lang="scss" scoped>
.el-switch {
  --el-switch-on-color: var(--el-color-primary);
  --el-switch-off-color: var(--el-border-color);
}
</style>
